# coding=utf-8
import re


def generate_page_url(template, page_no):
    # text = "https://www.amazon.com/s/ref=lp_289742_pg_2?rh=n%3A1055398%2Cn%3A%211063498%2Cn%3A284507%2Cn%3A289913%2Cn%3A289742&page=2&ie=UTF8&qid=1552525738"
    pattern = re.compile(r'lp_(\d+)+_pg_(\d+)', re.IGNORECASE)
    result = re.sub(pattern, lambda m: ('lp_%s_pg_%s' % (m.group(1), page_no)), template)

    pattern = re.compile(r'page=(\d+)', re.IGNORECASE)
    result = re.sub(pattern, lambda m: ('page=%s' % page_no), result)
    return result
